<template>
  <div id="app">
    <el-container class="layout-container">
      <!-- 顶部菜单栏 -->
      <el-header class="header">
        <div class="header-left">
          <div class="logo">
            <el-icon><Menu /></el-icon>
            <span>学习管理系统</span>
          </div>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <el-avatar
                v-if="avatarUrl"
                :size="30"
                :src="avatarUrl"
                class="user-avatar"
              />
              <el-avatar
                v-else
                :size="30"
                class="user-avatar"
              >
                {{ userInfo.name ? userInfo.name.charAt(0) : userInfo.username.charAt(0) }}
              </el-avatar>
              <span class="user-name">{{ userInfo.name || userInfo.username }}</span>
              <el-icon class="arrow-down"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 左侧功能模块栏 -->
        <el-aside class="sidebar" width="200px">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
            :router="false"
          >
            <el-menu-item index="/">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>

            <!-- 学习中心菜单项 -->
            <el-sub-menu index="study-center">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>学习中心</span>
              </template>
              <el-menu-item index="/study/courses">
                <el-icon><Collection /></el-icon>
                <span>课程中心</span>
              </el-menu-item>
              <el-menu-item index="/courses/manage" v-if="hasRole('LECTURER') || hasRole('ADMIN')">
                <el-icon><VideoPlay /></el-icon>
                <span>课程管理</span>
              </el-menu-item>
              <el-menu-item index="/study/profile" v-if="!hasRole('ADMIN') && !hasRole('LECTURER')">
                <el-icon><User /></el-icon>
                <span>学习档案</span>
              </el-menu-item>
              <el-menu-item index="/study/students/points" v-if="hasRole('ADMIN') || hasRole('LECTURER')">
                <el-icon><User /></el-icon>
                <span>学生积分</span>
              </el-menu-item>
              <el-menu-item index="/study/questions">
                <el-icon><ChatLineRound /></el-icon>
                <span>问答社区</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu v-if="hasRole('ADMIN')" index="system-config">
              <template #title>
                <el-icon><User /></el-icon>
                <span>用户管理</span>
              </template>
              <!-- 用户管理菜单项，只有管理员或有查看用户权限的人可见 -->
              <el-menu-item v-if="hasRole('ADMIN') || hasPermission('USER_READ')" index="/users">
                <el-icon><User /></el-icon>
                <span>用户列表</span>
              </el-menu-item>
              <!-- 密码管理菜单项，只有管理员或有管理密码权限的人可见 -->
              <el-menu-item v-if="hasRole('ADMIN') || hasPermission('USER_UPDATE')" index="/password-management">
                <el-icon><Key /></el-icon>
                <span>密码管理</span>
              </el-menu-item>
              <!-- 角色权限管理菜单项，只有管理员可见 -->
              <el-menu-item v-if="hasRole('ADMIN')" index="/role-permission-management">
                <el-icon><Setting /></el-icon>
                <span>角色权限管理</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 系统配置菜单项，只有管理员可见 -->
            <el-sub-menu v-if="hasRole('AUDITOR') || hasRole('ADMIN')" index="system-config">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统配置</span>
              </template>
              <el-menu-item  v-if="hasRole('AUDITOR') || hasRole('ADMIN')" index="/system-config/logs">日志记录</el-menu-item>
              <el-menu-item  v-if="hasRole('AUDITOR') || hasRole('ADMIN')" index="/system-config/status">系统状态</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <!-- 主内容区域 -->
        <el-main class="main-content">
          <router-view />
        </el-main>

      </el-container>

    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, ArrowDown, Menu, House, Key, Folder, Tickets, DataAnalysis, Setting, SwitchButton, Reading, Collection, ChatLineRound, VideoPlay } from '@element-plus/icons-vue'
import { initUser, hasPermission, hasRole, getCurrentUserRoles, getCurrentUser } from './utils/auth'
import request from '@/utils/request'

// 用户信息
const userInfo = ref({
  name: '',
  username: '',
  avatar: '',
  id: null
})

// 计算头像URL
const avatarUrl = computed(() => {
  // 确保userInfo中有id字段
  const userId = userInfo.value.id || (userInfo.value as any).id;
  if (userId && userInfo.value.avatar) {
    // 添加时间戳避免缓存
    const url = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/users/avatar/${userId}?t=${new Date().getTime()}`
    return url
  }
  return ''
})

// 活跃菜单项
const activeMenu = ref('/')

// 路由实例
const router = useRouter()
const route = useRoute()

// 页面加载时获取用户信息和设置当前菜单
onMounted(() => {
  // 初始化用户信息
  initUser()

  // 从后端API获取当前用户信息，确保获取最新的头像数据
  fetchCurrentUser(true) // 强制更新以确保获取最新数据

  // 设置当前活跃菜单
  activeMenu.value = route.path
})

// 监听路由变化，更新活跃菜单
router.afterEach((to) => {
  activeMenu.value = to.path
})

// 监听localStorage变化，重新初始化用户信息
window.addEventListener('storage', (event) => {
  if (event.key === 'userInfo') {
    try {
      initUser()
      // 从后端API获取最新用户信息，确保获取最新的头像数据
      fetchCurrentUser() // 使用智能更新策略
    } catch (error) {
      console.error('Error updating user info from storage event:', error)
    }
  }
})

// 监听路由变化，如果导航到登录页，清除用户信息
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    userInfo.value = { name: '', username: '' }
  }
  next()
})

// 处理菜单选择
const handleMenuSelect = (index: string) => {
  router.push(index)
}

// 处理用户下拉菜单命令
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      // 跳转到个人中心
      router.push('/profile')
      break
    case 'settings':
      // 跳转到系统设置
      ElMessage.info('系统设置功能待开发')
      break
    case 'logout':
      // 调用后端退出登录接口
      try {
        await fetch('http://localhost:8080/api/users/logout', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })
      } catch (error) {
        console.error('Logout API call failed:', error)
      }

      // 退出登录
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      // 重置用户信息
      userInfo.value = { name: '', username: '' }
      router.push('/login')
      ElMessage.success('已退出登录')
      break
  }
}

// 监听路由变化，检查用户信息更新
watch(route, () => {
  // 每次路由变化时检查用户信息
  const currentUser = getCurrentUser()
  if (currentUser) {
    // 只有当用户信息发生变化时才更新
    if (JSON.stringify(userInfo.value) !== JSON.stringify(currentUser)) {
      userInfo.value = {
        ...userInfo.value,
        ...currentUser
      }
    }
    // 特别检查头像信息
    else if (currentUser.avatar && userInfo.value.avatar !== currentUser.avatar) {
      userInfo.value.avatar = currentUser.avatar
    }
  }
})

// 获取当前用户信息（从后端API）
const fetchCurrentUser = async (forceUpdate = false) => {
  try {
    // 检查是否需要强制更新或距离上次更新时间过长
    const lastUpdate = localStorage.getItem('userLastUpdate')
    const now = Date.now()
    const updateInterval = 30 * 60 * 1000 // 30分钟更新间隔

    if (!forceUpdate && lastUpdate && (now - parseInt(lastUpdate)) < updateInterval) {
      // 如果不需要强制更新且时间间隔未到，直接使用localStorage数据
      const currentUser = getCurrentUser()
      if (currentUser) {
        userInfo.value = {
          ...userInfo.value,
          ...currentUser,
          username: currentUser.username,
          name: currentUser.name,
          id: currentUser.id,
          avatar: currentUser.avatar || ''
        }
      }
      return
    }

    // 从后端获取最新数据
    const response = await request.get('/api/users/current')
    userInfo.value = {
      ...userInfo.value,
      ...response.data,
      username: response.data.username,
      name: response.data.name,
      id: response.data.id,
      avatar: response.data.avatar || ''
    }

    // 更新localStorage中的用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      userInfo.avatar = response.data.avatar || ''
      userInfo.name = response.data.name
      localStorage.setItem('userInfo', JSON.stringify(userInfo))

      // 记录更新时间
      localStorage.setItem('userLastUpdate', now.toString())

      // 触发storage事件，通知其他组件更新
      window.dispatchEvent(new StorageEvent('storage', {
        key: 'userInfo',
        newValue: JSON.stringify(userInfo)
      }))
    }
  } catch (error) {
    console.error('Failed to fetch current user:', error)
    // 如果获取失败，回退到使用localStorage数据
    const currentUser = getCurrentUser()
    if (currentUser) {
      userInfo.value = {
        ...userInfo.value,
        ...currentUser,
        username: currentUser.username,
        name: currentUser.name,
        id: currentUser.id,
        avatar: currentUser.avatar || ''
      }
    }
  }
}
</script>

<style>
/* 全局样式 */
#app {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: auto;
}

.layout-container {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

.layout-container :deep(.el-container) {
  height: 100%;
}

.layout-container :deep(.el-header) {
  padding: 0;
}

.layout-container :deep(.el-aside) {
  height: calc(100% - 60px);
}

.layout-container :deep(.el-main) {
  padding: 0;
  background-color: #f5f7fa;
}

/* 顶部菜单栏样式 */
.header {
  background-color: #ffffff;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 60px; /* 明确设置高度 */
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.logo i {
  margin-right: 10px;
  font-size: 24px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  margin-right: 8px;
}

.user-name {
  margin-right: 8px;
  font-size: 14px;
}

.arrow-down {
  font-size: 12px;
}

/* 左侧功能模块栏样式 */
.sidebar {
  background-color: #ffffff;
  border-right: 1px solid #ebeef5;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

.sidebar-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
}

.sidebar-menu .el-menu-item i {
  margin-right: 10px;
  color: #606266;
}

.sidebar-menu .el-menu-item:hover {
  background-color: #ecf5ff;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
}

.sidebar-menu .el-menu-item.is-active i {
  color: #409eff;
}

/* 主内容区域样式 */
.main-content {
  background-color: #f5f7fa;
  padding: 0;
  height: calc(100% - 60px); /* 减去头部高度 */
  overflow-y: auto;
  margin: 0;
  width: 100%;
  min-height: calc(100vh - 60px);
}

.main-content :deep(.el-main) {
  padding: 0;
  background-color: #f5f7fa;
}
</style>
